<template>
  <div id="">
    <headerbox :headerTitle="'群聊'" :hasBack="true" :headerRightTxt="'。。。'" @headerRightEvent="headerRightEvent"></headerbox>
    <div class="messageBox p10" id="messageList">
      <!-- <p class="getHistoryMsgTip" @click="getMsgTip">获取历史消息</p> -->
        <!-- <li class="sendLi" v-for="elem in sendList" :key="elem.key" v-html="elem">

        </li> -->
        <!-- <li class="reveiveLi" v-for="elem in sendList" :key="elem.key">
          <div class="" v-html="elem">

          </div>
        </li> -->
        <div class="msgDiv" v-for="elem in sendList" :key="elem.key">
          <div class="mb10" v-html="elem">

          </div>
        </div>
    </div>
    <div class="fixedButtom msgBtn">
      <input type="text" name="" v-model="messageTxt" @keyup.enter="sendMsg">
      <button type="button" name="button" @click="sendMsg">发送</button>
    </div>
  </div>
</template>
<script>
import {mapState,mapMutations} from 'vuex';
/**
消息模板
*/
let funcSend = (data,sendImg)=>{    //接收消息
  let sendTxt =
  `<div class="msgCont sendLi">
    <img src="${sendImg}" alt="" class="msgHeadPic">
    <div class="msgCon p10">
      ${data}
    </div>
  </div>`;
  return sendTxt;
};
let funcReceive = (data,sendImg)=>{   //发送消息
  let sendTxt =
  `<div class="msgCont reveiveLi">
    <div class="msgCon p10">
      ${data}
    </div>
    <img src="${sendImg}" class="msgHeadPic">
  </div>`;
  return sendTxt;
};

export default {
  name: "",
  data: () => ({
    messageTxt:'',      //发送的消息内容
    targetId:'',        //融云聊天目标id
    rongToken:'',       //用户的融云token
    userId:'',          //当前用户id
    sendList:[],
    sendImg: require('@/assets/groupImage/headportrait.png'),
  }),
  computed:{
    ...mapState({
      rongLoad:state=>state.friendRongStore.rongLoad,
    })
  },
  methods: {
    // 查看群信息
    headerRightEvent() {
      this.$router.push({path:'/groupInfo',query:{groupId:this.targetId}});
    },
    // 融云初始化
    init() {
      let self = this;
      RongIMLib.RongIMClient.init(this.$globalData.rongAppkey);
      // 设置连接监听状态 （ status 标识当前连接状态 ）
       // 连接状态监听器
       RongIMClient.setConnectionStatusListener({
          onChanged: function (status) {
              switch (status) {
                  case RongIMLib.ConnectionStatus.CONNECTED:
                      console.log('链接成功');
                      break;
                  case RongIMLib.ConnectionStatus.CONNECTING:
                      console.log('正在链接');
                      break;
                  case RongIMLib.ConnectionStatus.DISCONNECTED:
                      console.log('断开连接');
                      break;
                  case RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT:
                      console.log('其他设备登陆');
                      break;
                    case RongIMLib.ConnectionStatus.DOMAIN_INCORRECT:
                      console.log('域名不正确');
                      break;
                  case RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE:
                    console.log('网络不可用');
                    break;
                  }
          }});

       // 消息监听器
       RongIMClient.setOnReceiveMessageListener({
          // 接收到的消息
          onReceived: function (message) {
              // 判断消息类型
              switch(message.messageType){
                  case RongIMClient.MessageType.TextMessage:
                      // message.content.content => 消息内容
                      console.log(message);
                      // let content = message.content.content;    //消息内容
                      let content = funcSend(message.content.content,self.sendImg);
                      self.$nextTick(()=>{
                        self.sendList.push(content);
                        let chatHeight = document.getElementById('messageList').offsetHeight;
                        console.log(chatHeight);
                        document.body.scrollTop = document.documentElement.scrollTop = chatHeight;
                      })

                      break;
                  case RongIMClient.MessageType.VoiceMessage:
                      // 对声音进行预加载
                      // message.content.content 格式为 AMR 格式的 base64 码
                      break;
                  case RongIMClient.MessageType.ImageMessage:
                     // message.content.content => 图片缩略图 base64。
                     // message.content.imageUri => 原图 URL。
                     break;
                  case RongIMClient.MessageType.DiscussionNotificationMessage:
                     // message.content.extension => 讨论组中的人员。
                     break;
                  case RongIMClient.MessageType.LocationMessage:
                     // message.content.latiude => 纬度。
                     // message.content.longitude => 经度。
                     // message.content.content => 位置图片 base64。
                     break;
                  case RongIMClient.MessageType.RichContentMessage:
                     // message.content.content => 文本消息内容。
                     // message.content.imageUri => 图片 base64。
                     // message.content.url => 原图 URL。
                     break;
                  case RongIMClient.MessageType.InformationNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ContactNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.ProfileNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandNotificationMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.CommandMessage:
                      // do something...
                     break;
                  case RongIMClient.MessageType.UnknownMessage:
                      // do something...
                     break;
                  default:
                      // do something...
              }
          }
      });
    },
    RongConnect() {
      let self = this;
      RongIMClient.connect(this.rongToken, {    //融云链接服务器
         onSuccess: function(userId) {
           console.log("Login successfully." + userId);
           self.getHistoryMsg(self.targetId);    //获取历史消息
         },
         onTokenIncorrect: function() {
           console.log('token无效');
         },
         onError:function(errorCode){
               var info = '';
               switch (errorCode) {
                 case RongIMLib.ErrorCode.TIMEOUT:
                   info = '超时';
                   break;
                 case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                   info = '未知错误';
                   break;
                 case RongIMLib.ErrorCode.UNACCEPTABLE_PaROTOCOL_VERSION:
                   info = '不可接受的协议版本';
                   break;
                 case RongIMLib.ErrorCode.IDENTIFIER_REJECTED:
                   info = 'appkey不正确';
                   break;
                 case RongIMLib.ErrorCode.SERVER_UNAVAILABLE:
                   info = '服务器不可用';
                   break;
               }
               console.log(errorCode);
             }
       });
    },
    // 发送消息
    sendMsg() {
      console.log(this.messageTxt);
      let self = this;
      // console.log(func(this.messageTxt));
      let targetId = this.targetId; // 目标 Id
      var msg = new RongIMLib.TextMessage({content:this.messageTxt,extra:"聊天信息"});
      var conversationtype = RongIMLib.ConversationType.GROUP; // 群聊,其他会话选择相应的消息类型即可。
      RongIMClient.getInstance().sendMessage(conversationtype, targetId, msg, {
               onSuccess: function (message) {
                   //message 为发送的消息对象并且包含服务器返回的消息唯一Id和发送消息时间戳
                   console.log("Send successfully");
                   console.log(message);
                   let content = funcReceive(message.content.content,self.sendImg);
                   self.sendList.push(content);
                   self.messageTxt = '';
                   self.$nextTick(()=>{
                     let chatHeight = document.getElementById('messageList').offsetHeight;
                     console.log(chatHeight);
                     // window.scroll = () => {
                       document.body.scrollTop = document.documentElement.scrollTop = chatHeight;
                     // }
                   })
               },
               onError: function (errorCode,message) {
                   var info = '';
                   switch (errorCode) {
                       case RongIMLib.ErrorCode.TIMEOUT:
                           info = '超时';
                           break;
                       case RongIMLib.ErrorCode.UNKNOWN_ERROR:
                           info = '未知错误';
                           break;
                       case RongIMLib.ErrorCode.REJECTED_BY_BLACKLIST:
                           info = '在黑名单中，无法向对方发送消息';
                           break;
                       case RongIMLib.ErrorCode.NOT_IN_DISCUSSION:
                           info = '不在讨论组中';
                           break;
                       case RongIMLib.ErrorCode.NOT_IN_GROUP:
                           info = '不在群组中';
                           break;
                       case RongIMLib.ErrorCode.NOT_IN_CHATROOM:
                           info = '不在聊天室中';
                           break;
                       default :
                           info = x;
                           break;
                   }
                   console.log('发送失败:' + info);
               }
           }
       );
    },
    // 获取历史消息
    getHistoryMsg(targetId) {
      let self = this;
      var conversationType = RongIMLib.ConversationType.GROUP; //群组聊天,其他会话选择相应的消息类型即可。
      var targetId = targetId; // 想获取自己和谁的历史消息，targetId 赋值为对方的 Id。
      var timestrap = 0; // 默认传 null，若从头开始获取历史消息，请赋值为 0 ,timestrap = 0;
      var count = 20; // 每次获取的历史消息条数，范围 0-20 条，可以多次获取。
      RongIMLib.RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, {
        onSuccess: function(list, hasMsg) {
             // list => Message 数组。
          // hasMsg => 是否还有历史消息可以获取。
          console.log(list);
          let content = '';
          for (var key in list) {
            if(list[key].content.messageName == "TextMessage"){   //文本消息类型
              let content = list[key].content.content;    //消息内容
              // 判断是否接收的消息，通过当前用户id判断 senderUserId的来源
              if (list[key].senderUserId == self.userId) {    //自己发送的消息
                content = funcReceive(list[key].content.content,self.sendImg);
              }else {   //接收的消息
                content = funcSend(list[key].content.content,self.sendImg);
              }
              self.sendList.push(content);
              self.$nextTick(()=>{
                let chatHeight = document.getElementById('messageList').offsetHeight;
                console.log(chatHeight);
                // window.scroll = () => {
                  document.body.scrollTop = document.documentElement.scrollTop = chatHeight;
                // }
              })

            }

          }
          console.log(hasMsg);
        },
        onError: function(error) {
          console.log("GetHistoryMessages,errorcode:" + error);
        }
      });
    },
    getMsgTip() {
      console.log('获取历史消息');
      this.init();    //融云初始化
      this.RongConnect();
      this.getHistoryMsg(this.targetId);
    }
  },
  mounted() {
    //do something after mounting vue instance
    let self = this;
    let targetId = this.$route.query.groupId;     //目标id为群组id
    this.targetId = targetId;   //聊天对象的id
    let xlyd_loginInfo = JSON.parse(window.localStorage.getItem('xlyd_loginInfo'));
    this.userId = xlyd_loginInfo.id;    //当前用户id
    this.rongToken = xlyd_loginInfo.rongToken;      //融云的token

    this.$nextTick(()=>{
      console.log('加载');
      this.init();    //融云初始化
      this.RongConnect();
      this.getMsgTip();
    })


  }
}
</script>
<style lang="scss">
.getHistoryMsgTip{
  font-size: 12px;
  color: $lightColor;
  text-align: center;
  padding-bottom: 10px;
}
.msgBtn{
  @include flex;
  justify-content: space-between;
  background: white;
  input{
    width: 80%;
    height: 40px;
    line-height: 40px;
    padding: 0 10px;
  }
  button{
    background: $blueColor;
    color: white;
    width: 16%;
    height: 40px;
  }
}
.messageBox{
  margin-bottom: 0;
  .msgDiv .msgCont{
    @include flex;
    align-items: flex-start;
    margin-bottom: 10px;
    .msgHeadPic{
      width: 40px;
      height: 40px;
      border-radius: 100%;
    }
    .msgCon{
      padding: 10px;
      background: white;
      border-radius: 4px;
      margin-left: 10px;
      position: relative;
      // @include flexcell;
      display: inline-block;
      &::before{
        position: absolute;
        top: 8px;
        left: -10px;
        z-index: 2;
        content: '';
        border-right: 10px solid white;
        border-top: 6px solid transparent;
        border-bottom: 6px solid transparent;
        width: 0; height: 0;
      }
    }
    &.reveiveLi{
      .msgCon{
        background: $lightBlue;
        margin-left: auto;
        margin-right: 10px;
        &::before{
          left: auto;
          right: -10px;
          border-left: 10px solid $lightBlue;
          border-right: none;
        }
      }
    }
  }

}
</style>
